<template>
  <container type="ghost">
    <div class="theme-tab-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" >
        <el-form-item v-for="item in settingKeys"
                      :key="item.id"
                      :name="item.id + ''"
                      :label="item.label"
                      :prop="item.id">
          <el-select v-if="item.compType=='select'||item.compType=='radio'||item.compType=='checkbox'"
                     v-model="queryParams[item.id]" placeholder="请选择">
            <el-option
              v-for="op in item.options"
              :key="op.value"
              :label="op.label"
              :value="op.value">
            </el-option>
          </el-select>
          <el-cascader v-else-if="item.compType=='cascader'"
            v-model="queryParams[item.id]"
            :options="item.options">
          </el-cascader>
          <el-input v-else
            v-model="queryParams[item.id]"
            placeholder=""
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="theme-main-container">
      <el-row :gutter="10" class="mb8">
        <el-col v-for="item in btnDatas" :key="item.id" :span="1.5">
          <el-button v-if="item.btnNo=='add' && item.state=='1'" type="primary" size="mini"
                     plain icon="el-icon-circle-plus"  @click="handlerAdd()">
            {{item.btnName}}</el-button>
          <el-button v-else-if="item.btnNo=='edit' && item.state=='1'" type="success" size="mini"
                     plain icon="el-icon-edit"  @click="handlerEdit()">
            {{item.btnName}}</el-button>
          <el-button v-else-if="item.btnNo=='delete' && item.state=='1'" type="danger" size="mini"
                     plain icon="el-icon-delete"  @click="handlerDelete()">
            {{item.btnName}}</el-button>
          <el-button v-else-if="item.btnNo=='exp' && item.state=='1'" type="primary" size="mini"
                     plain icon="el-icon-share"  @click="handlerExport()">
            {{item.btnName}}</el-button>
        </el-col>
      </el-row>
      <el-table
        id="table"
        :data="dataTable"
        row-key="id"
        border
        style="width: 100%;padding-top: 5px"
        @selection-change="handleSelectionChange"
        default-expand-all>
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="60">
        </el-table-column>
        <el-table-column v-for="item in tableColumns" :key="item.id" v-bind="item"
                         width="150" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-if="item.compType=='select'||item.compType=='radio'||item.compType=='checkbox'">
              <span>{{ parseString(item,scope.row[item.id]) }}</span>
            </div>
            <div v-else-if="item.compType=='Switch'">
              <span>{{ parseString(item,scope.row[item.id]) }}</span>
            </div>
            <div v-else-if="item.id=='id'">
              <span v-if="false">{{ scope.row[item.id] }}</span>
            </div>
            <span v-else>{{ scope.row[item.id] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template slot-scope="scope">
            <div class="operation-btn">
              <el-button icon="el-icon-edit" @click="handlerView(scope.row)"  type="text">查看</el-button>
              <el-popconfirm title="您确定要删除吗？"
                             @confirm="handlerDelete(scope.row)">
                <el-button icon="el-icon-delete" slot="reference" size="mini" type="text" class="btn-danger">删除</el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="loadData"
      />
    </div>

    <!-- 新增对话框 -->
    <el-drawer v-if="dialogVisible==true"
               :visible.sync="dialogVisible"
               :with-header="true"
               :title="title"
               size="70%"
               :append-to-body="false"
               destroy-on-close>
      <div class="drawer-content" style="width: 100% !important;">
        <formpage @cloaseDialog="cloaseDialog"
                  ref="formPage"
                  :dataJson="dataItem"
                  :bid="bid"
                  :mapList="mapList"
                  :form_type="form_type"
                  :mapConfig="mapConfig"></formpage>
      </div>

      <div class="drawer-footer">
        <el-button @click="dialogVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="handlerSave"> 确定 </el-button>
      </div>
    </el-drawer>
    <!--查看对话框-->
    <el-drawer v-if="handView==true"
               :visible.sync="handView"
               :with-header="true"
               title="详情"
               size="70%"
               :append-to-body="false"
               destroy-on-close>
      <div class="drawer-content" style="width: 100% !important;">
        <pageview @cloaseDialog="cloaseDialog"
                  ref="pageview"
                  :dataJson="dataItem"
                  :bid="bid"
                  :mapList="mapList"
                  :form_type="form_type"
                  :mapConfig="mapConfig"></pageview>
      </div>

      <div class="drawer-footer">
        <el-button @click="handView = false"> 取消 </el-button>
      </div>
    </el-drawer>
  </container>
</template>

<script>
import dictTag from "@/components/dictTag";
import {parseTime, itemReadOnly, exp} from "@/utils/comm";
import formpage from "@/views/form/formPage/page";
import pageview from "@/views/form/formPage/pageview";
import {getFormAppSetting, getApplicationData, getGenerWork, deleteGenerWork} from "@/api/process/processFrom";
import {saveFormDataJson} from '@api/reviewpage/reviewpage';
import Pagination from '@/components/Pagination';

export default {
  name: "formApplication",
  components:{dictTag,formpage,pageview,Pagination},
  data(){
    return{
      total:0,
      dialogVisible:false,
      title:"",
      handView:false,
      //表单id
      applocationId:"",
      //勾选的行
      selectData:[],
      //表数据
      dataTable:[],
      //系统按钮
      btnDatas:[],
      //自定义按钮
      btnParams:[],
      //显示字段
      tableColumns:[],
      //查询条件集合
      settingKeys:[],
      // 查询参数
      queryParams: {
        pageNum:1,
        pageSize:10
      },
      //表单json
      form_json:Object,
      //表单数据
      dataItem:Object,
      //数据id
      bid:'',
      //字段列表
      mapList:[],
      //表单类型
      form_type:"0",
      //表单基本信息
      mapConfig:Object
    }
  },
  mounted(){
    this.loadData();
  },
  methods:{
    /**
     * 加载数据
     */
    async loadData(){
      this.applocationId=this.$route.meta.query;
      const res=await getFormAppSetting(this.applocationId);
      if(res.error=="200"){
        //按钮
        const btns=JSON.parse(res.result.btns);
        //系统按钮
        this.btnDatas=btns.toolbar;
        //自定义按钮
        this.btnParams=btns.selfbar;
        //显示的字段
        this.tableColumns=JSON.parse(res.result.cols);
        //查询字段
        this.settingKeys=JSON.parse(res.result.searchRules);
        //存储表
        this.queryParams.mainTable=res.result.form_data_table;
        //表单结构
        this.form_json=res.result.form_json;
        //设置查询参数
        this.queryParams.settingKeys=this.settingKeys;
        //查询数据
        this.queryParams.cols=this.tableColumns;
        this.settingKeys.forEach(item => {
          this.$set(this.queryParams,item.id,"");
        });
        this.search();
      }
      else{
        this.$message.warning(res.msg);
      }
    },
    async search(){
      const data=await getApplicationData(this.queryParams);
      if(data.error=="200"){
        this.dataTable=data.result.list;
        this.total=data.result.total;
      }
      else{
        this.$message.warning(data.msg);
      }
    },
    /**
     * 新增
     */
    handlerAdd(){
      this.title="新增";
      const mapJson = JSON.parse(this.form_json);
      this.mapConfig = mapJson.config;
      this.mapList = mapJson.list;
      this.dataItem={};
      this.dialogVisible=true;
    },
    async handlerEdit(){
      let row={};
      if(this.selectData.length==1){
        row.id=this.selectData[0].id;
      }
      else{
        this.$message.warning("请选择一条数据，再执行查看");
        return;
      }
      this.title="编辑";
      const mapJson = await this.getDataById(row.id);
      if(mapJson==""){
        this.$message.warning("编辑失败");
        return;
      }
      debugger;
      this.mapConfig = mapJson.config;
      this.mapList = mapJson.list;
      this.dialogVisible=true;
    },
    /**
     * 查看详情
     * @param row
     * @returns {Promise<void>}
     */
    async handlerView(row){
      const mapJson = await this.getDataById(row.id);
      if(mapJson==""){
        this.$message.warning("查看详情失败");
        return;
      }
      this.mapConfig = mapJson.config;
      this.mapList = itemReadOnly(mapJson.list);
      this.handView=true;
    },
    /**
     * 保存
     */
    handlerSave(){
      let json=this.$refs.formPage.save();
      let mapConfig = {
        config: this.mapConfig,
        list: json.keyList
      };
      saveFormDataJson(json.id,0,''
        ,'',JSON.stringify(mapConfig),JSON.stringify(json.keyValueList)).then(res=>{
        if(res.error=="200"){
          this.$message.success("保存成功");
          this.dialogVisible=false;
          this.search();
        }
        else{
          this.$message.error("保存失败");
        }
      });
    },
    /**
     * 删除
     * @param id
     * @returns {Promise<void>}
     */
    async handlerDelete(row){
      if(row==undefined||row==null){
        if(this.selectData.length<=0){
          this.$message.warning("请选择要删除的数据");
          return ;
        }
      }
      else{
        this.selectData.push(row);
      }
      let itemId="";
      this.selectData.forEach(item => {
        itemId+=item.id+",";
      });
      const params={
        frmId:this.applocationId,
        list:itemId
      };
      const res= await deleteGenerWork(params);
      if (res.error == '200') {
        this.$message.success("删除成功");
        this.resetQuery();
      }
    },
    async getDataById(id){
      const res=await getGenerWork({id:id});
      if (res.error == '200') {
        const mapJson = JSON.parse(res.result.map_json);
        this.dataItem=JSON.parse(res.result.data_json);
        return mapJson;
      }
      else
        return "";
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.search();
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        no: undefined,
        name: "",
        dataType: "0",
        status: "1",
        doc: "",
        remark: ""
      };
    },
    handleSelectionChange(row){
      this.selectData=row;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    parseTime2(data){
      return parseTime(data);
    },
    parseString(obj,val){
      let objVal="";
      if(obj.compType=="Switch"){
        if(val=="false")
          return "否";
        else
          return "是";
      }
      else{
        obj.options.forEach(item => {
          if(item.value.toString()==val)
            return objVal=item.label;
        });
      }
      return objVal;
    },
    cloaseDialog(){
      this.dialogVisible=false;
      this.handView=false;
      this.loadData();
    },
    //导出
    handlerExport() {
      this.$confirm("确定要导出文件到Excel?", "导出提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }).then(() => {
        setTimeout(() => {
          let tables = document.getElementById('table');   //这里是绑定元素，输入你要导出的table表格的id
          exp(tables,this);
        }, 1000)
      })
    }
  }
}
</script>

<style scoped>

</style>

